/**
 * @description: 控制用户操作权限
 */
import type { Directive } from 'vue';

import { useUserStore } from '@/store/user';
import { intersection } from '@/utils/index';
import { isPlainArray } from '@/utils/validate';

export const permission: Directive = {
  mounted(el: any, binding: any) {
    const userStore = useUserStore();
    const authKeys: string[] = userStore.authKeys;

    const { value } = binding; // 指令接收到的值
    if (value && typeof value === 'string') {
      const hasPermission = authKeys.includes(value);
      if (!hasPermission) {
        el.remove();
      }
    } else if (value && isPlainArray(value)) { // 指令是数组
      const hasPermission = intersection(authKeys, value).length > 0;
      if (!hasPermission) {
        el.remove();
      }
    } else {
      throw new Error(`need roles! Like
        v-permission='[FM_FILE.FC_CAD_PREVIEW.R]' or
        v-permission='FM_FILE.FC_CAD_PREVIEW.R'`);
    }
  },
};
